package NC53_删除链表的倒数第n个节点;

import java.util.*;

class ListNode {
    int val;
    ListNode next = null;
}

public class Solution {
    /**
     *
     * @param head ListNode类
     * @param n int整型
     * @return ListNode类
     */
    public ListNode removeNthFromEnd (ListNode head, int n) {
        // write code here
        if (head == null){
            return null;
        }
        int len = length(head);
        int delete = len - n;

        ListNode cur = head;

        if (n == len){
            return head.next;
        }
        int i = 0;
        while (cur != null){
            i++;
            if (i == delete){
                cur.next = cur.next.next;
            }
            cur = cur.next;
        }
        return head;

    }

    private int length(ListNode head) {
        int len = 0;
        while (head != null){
            len++;
            head = head.next;
        }
        return len;
    }
}